<template>
  <div class="home-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar 
      title="推普活动" 
      fixed
      placeholder
    >
      <template #right>
        <van-icon name="search" @click="handleSearch" />
        <van-icon name="bell-o" @click="handleNotification" class="ml-4" />
      </template>
    </van-nav-bar>

    <!-- 主内容区域 -->
    <div class="page-content">
      <!-- 轮播图区域 -->
      <div class="banner-section">
        <!-- 加载状态 -->
        <div v-if="bannerLoading" class="banner-loading">
          <van-skeleton title :row="0" class="banner-skeleton" />
        </div>

        <!-- 轮播图内容 -->
        <van-swipe
          v-else-if="bannerList.length > 0"
          :autoplay="3000"
          indicator-color="white"
          class="banner-swipe"
          @change="onBannerChange"
        >
          <van-swipe-item v-for="(banner, index) in bannerList" :key="banner.id">
            <div class="banner-item" @click="handleBannerClick(banner)">
              <van-image
                :src="banner.image"
                :alt="banner.title"
                fit="cover"
                class="banner-image"
                :loading-icon="'photo'"
                :error-icon="'photo-fail'"
                @load="onBannerImageLoad(banner)"
                @error="onBannerImageError(banner)"
              />
              <div class="banner-overlay">
                <h3 class="banner-title">{{ banner.title }}</h3>
                <p class="banner-desc">{{ banner.description }}</p>
              </div>
            </div>
          </van-swipe-item>
        </van-swipe>

        <!-- 空状态 -->
        <div v-else class="banner-empty">
          <van-empty description="暂无轮播图" />
        </div>
      </div>

      <!-- 核心功能区 -->
      <div class="function-section">
        <div class="function-grid">
          <div 
            v-for="func in functionList" 
            :key="func.key"
            class="function-item"
            @click="handleFunctionClick(func)"
          >
            <div class="function-icon" :style="{ backgroundColor: func.bgColor }">
              <van-icon :name="func.icon" :color="func.iconColor" size="6vw" />
            </div>
            <span class="function-name">{{ func.name }}</span>
          </div>
        </div>
      </div>

      <!-- 推荐内容区域 -->
      <div class="recommend-section">
        <div class="section-header">
          <h2 class="section-title">推荐内容</h2>
          <span class="more-link" @click="handleMoreRecommend">更多 <van-icon name="arrow" /></span>
        </div>
        <div class="recommend-list">
          <div 
            v-for="item in recommendList" 
            :key="item.id"
            class="recommend-item"
            @click="handleRecommendClick(item)"
          >
            <img :src="item.cover" :alt="item.title" class="recommend-cover" />
            <div class="recommend-content">
              <h3 class="recommend-title">{{ item.title }}</h3>
              <p class="recommend-desc">{{ item.description }}</p>
              <div class="recommend-meta">
                <div class="rating">
                  <van-icon name="star" color="#ffd21e" />
                  <span>{{ item.rating }}</span>
                </div>
                <span class="study-count">{{ item.studyCount }}人学习</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 最新活动区域 -->
      <div class="activity-section">
        <div class="section-header">
          <h2 class="section-title">最新活动</h2>
          <span class="more-link" @click="handleMoreActivity">更多 <van-icon name="arrow" /></span>
        </div>
        <div class="activity-list">
          <div 
            v-for="activity in activityList" 
            :key="activity.id"
            class="activity-item"
            @click="handleActivityClick(activity)"
          >
            <img :src="activity.poster" :alt="activity.title" class="activity-poster" />
            <div class="activity-content">
              <h3 class="activity-title">{{ activity.title }}</h3>
              <p class="activity-desc">{{ activity.description }}</p>
              <div class="activity-meta">
                <span class="deadline">报名截止：{{ formatDate(activity.endTime) }}</span>
                <span class="join-btn">立即报名 <van-icon name="arrow" /></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="HomePage" lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { HomeService } from '@/api/services';
import type { Banner, FunctionModule, Course, Activity } from '@/api/index';

const router = useRouter();

// 响应式数据
const bannerList = ref<Banner[]>([]);
const functionList = ref<FunctionModule[]>([]);
const recommendList = ref<Course[]>([]);
const activityList = ref<Activity[]>([]);
const loading = ref(false);
const bannerLoading = ref(false);
const currentBannerIndex = ref(0);

// 默认数据（作为fallback）
const defaultBanners: Banner[] = [
  {
    id: 1,
    title: '普通话水平测试',
    description: '专业测试系统，精准评估您的普通话水平',
    image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/a22afdc01c3ca4153ab76025bc6bed40.png',
    link: '/detection',
    sort: 1,
    status: 'active'
  },
  {
    id: 2,
    title: 'AI智能评测',
    description: '先进AI技术，精准分析发音问题',
    image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/fa37b243329b9a3809ab23469116c32b.png',
    link: '/detection',
    sort: 2,
    status: 'active'
  },
  {
    id: 3,
    title: '系统化学习',
    description: '丰富课程资源，随时随地提升普通话',
    image: 'https://design.gemcoder.com/staticResource/echoAiSystemImages/6ad45ec982c8041d724c29aefd9219ce.png',
    link: '/study',
    sort: 3,
    status: 'active'
  }
];

const defaultFunctions: FunctionModule[] = [
  {
    key: 'detection',
    name: '语音检测',
    icon: 'volume-o',
    bgColor: '#e3f2fd',
    iconColor: '#1989fa',
    route: '/detection',
    sort: 1,
    enabled: true
  },
  {
    key: 'study',
    name: '学习中心',
    icon: 'book-o',
    bgColor: '#e8f5e8',
    iconColor: '#07c160',
    route: '/list',
    sort: 2,
    enabled: true
  },
  {
    key: 'game',
    name: '小游戏',
    icon: 'fire-o',
    bgColor: '#f3e5f5',
    iconColor: '#9c27b0',
    route: '/game',
    sort: 3,
    enabled: true
  },
  {
    key: 'daily',
    name: '每日一句',
    icon: 'chat-o',
    bgColor: '#fff3e0',
    iconColor: '#ff9800',
    route: '/daily',
    sort: 4,
    enabled: true
  }
];

// 加载轮播图数据
const loadBanners = async () => {
  try {
    bannerLoading.value = true;
    console.log('🎠 开始加载轮播图数据...');

    const banners = await HomeService.getBanners();

    if (banners && banners.length > 0) {
      // 过滤有效的轮播图（状态为active且有图片）
      const validBanners = banners.filter((banner: Banner) =>
        banner.status === 'active' &&
        banner.image &&
        banner.title
      );

      if (validBanners.length > 0) {
        // 按sort字段排序
        bannerList.value = validBanners.sort((a: Banner, b: Banner) => a.sort - b.sort);
        console.log('✅ 轮播图加载成功:', bannerList.value.length, '个');
      } else {
        console.log('⚠️ 没有有效的轮播图，使用默认数据');
        bannerList.value = defaultBanners;
      }
    } else {
      console.log('⚠️ 轮播图接口返回空数据，使用默认数据');
      bannerList.value = defaultBanners;
    }
  } catch (error) {
    console.error('❌ 加载轮播图失败:', error);
    bannerList.value = defaultBanners;
    showToast('轮播图加载失败，显示默认内容');
  } finally {
    bannerLoading.value = false;
  }
};

// 加载首页数据
const loadHomeData = async () => {
  try {
    loading.value = true;

    // 并行加载轮播图和其他数据
    const [_, data] = await Promise.all([
      loadBanners(),
      HomeService.loadHomeData()
    ]);

    if (data) {
      functionList.value = data.functions.length > 0 ? data.functions : defaultFunctions;
      recommendList.value = data.recommendations || [];
      activityList.value = data.activities || [];
    } else {
      // 使用默认数据
      functionList.value = defaultFunctions;
      recommendList.value = [];
      activityList.value = [];
    }
  } catch (error) {
    console.error('加载首页数据失败:', error);
    // 使用默认数据
    functionList.value = defaultFunctions;
    recommendList.value = [];
    activityList.value = [];
  } finally {
    loading.value = false;
  }
};

// 事件处理函数
const handleSearch = () => {
  showToast('搜索功能开发中...');
};

const handleNotification = () => {
  showToast('通知功能开发中...');
};

const handleBannerClick = (banner: Banner) => {
  console.log('🎠 点击轮播图:', banner.title);

  if (banner.link) {
    // 统计点击事件（可选）
    trackBannerClick(banner);

    // 判断链接类型
    if (banner.link.startsWith('http')) {
      // 外部链接，在新窗口打开
      window.open(banner.link, '_blank');
    } else {
      // 内部路由跳转
      router.push(banner.link);
    }
  } else {
    showToast('该轮播图暂无链接');
  }
};

// 轮播图切换事件
const onBannerChange = (index: number) => {
  currentBannerIndex.value = index;
  console.log('🎠 轮播图切换到:', index);
};

// 轮播图图片加载成功
const onBannerImageLoad = (banner: Banner) => {
  console.log('🖼️ 轮播图图片加载成功:', banner.title);
};

// 轮播图图片加载失败
const onBannerImageError = (banner: Banner) => {
  console.error('❌ 轮播图图片加载失败:', banner.title, banner.image);
  showToast('图片加载失败');
};

// 统计轮播图点击（可选功能）
const trackBannerClick = (banner: Banner) => {
  // 这里可以添加统计代码，比如发送到分析服务
  console.log('📊 轮播图点击统计:', {
    bannerId: banner.id,
    title: banner.title,
    link: banner.link,
    timestamp: new Date().toISOString()
  });
};

const handleFunctionClick = (func: FunctionModule) => {
  if (func.route && func.enabled) {
    router.push(func.route);
  }
};

const handleRecommendClick = (item: Course) => {
  showToast(`查看课程：${item.title}`);
};

const handleActivityClick = (activity: Activity) => {
  showToast(`查看活动：${activity.title}`);
};

// 页面初始化
onMounted(() => {
  loadHomeData();
});

const handleMoreRecommend = () => {
  showToast('更多推荐内容开发中...');
};

const handleMoreActivity = () => {
  showToast('更多活动内容开发中...');
};

const formatDate = (dateStr: string) => {
  return new Date(dateStr).toLocaleDateString('zh-CN');
};
</script>

<style scoped lang="scss">
.home-page {
  min-height: 100vh;
  background-color: #f7f8fa;

  .van-nav-bar {
    background-color: #1989fa;
    
    :deep(.van-nav-bar__title) {
      color: white;
      font-weight: 600;
    }
    
    :deep(.van-icon) {
      color: white;
    }
  }
}

.page-content {
  padding: 4.26667vw;
  padding-bottom: 21.33333vw; // 为底部导航留空间
}

// 轮播图区域
.banner-section {
  margin-bottom: 6.4vw;

  .banner-loading {
    height: 48vw;
    border-radius: 2.13333vw;
    overflow: hidden;

    .banner-skeleton {
      height: 100%;
      border-radius: 2.13333vw;
    }
  }

  .banner-swipe {
    height: 48vw;
    border-radius: 2.13333vw;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .banner-item {
    position: relative;
    height: 100%;
    cursor: pointer;
    transition: transform 0.2s ease;

    &:active {
      transform: scale(0.98);
    }
  }

  .banner-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: opacity 0.3s ease;

    &.van-image--loading,
    &.van-image--error {
      background: #f7f8fa;
    }
  }

  .banner-overlay {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
    padding: 4.26667vw;
    color: white;
  }

  .banner-title {
    font-size: 4.8vw;
    font-weight: 600;
    margin-bottom: 1.06667vw;
    line-height: 1.3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .banner-desc {
    font-size: 3.2vw;
    opacity: 0.9;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .banner-empty {
    height: 48vw;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f7f8fa;
    border-radius: 2.13333vw;
    border: 1px dashed #d9d9d9;
  }
}

// 功能区域
.function-section {
  margin-bottom: 6.4vw;
  
  .function-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    gap: 4vw;
    padding: 0 2vw;
  }
  
  .function-item {
    background: white;
    border-radius: 4vw;
    padding: 6vw 4vw;
    text-align: center;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    cursor: pointer;
    transition: all 0.3s ease;
    min-height: 32vw;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    &:active {
      transform: scale(0.95);
    }

    &:hover {
      transform: translateY(-1vw);
      box-shadow: 0 4vw 20vw rgba(0, 0, 0, 0.12);
    }
  }

  .function-icon {
    width: 16vw;
    height: 16vw;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 3vw;
    box-shadow: 0 1vw 3vw rgba(0, 0, 0, 0.1);
  }

  .function-name {
    font-size: 3.5vw;
    font-weight: 600;
    color: #323233;
    line-height: 1.2;
  }
}

// 推荐内容区域
.recommend-section {
  margin-bottom: 6.4vw;
}

// 活动区域
.activity-section {
  margin-bottom: 6.4vw;
}

// 通用区域样式
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4.26667vw;
  
  .section-title {
    font-size: 4.8vw;
    font-weight: 600;
    color: #323233;
  }
  
  .more-link {
    font-size: 3.2vw;
    color: #969799;
    display: flex;
    align-items: center;
    cursor: pointer;
    
    .van-icon {
      margin-left: 1.06667vw;
      font-size: 2.66667vw;
    }
  }
}

// 推荐列表
.recommend-list {
  .recommend-item {
    background: white;
    border-radius: 2.13333vw;
    padding: 4.26667vw;
    margin-bottom: 3.2vw;
    display: flex;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    cursor: pointer;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .recommend-cover {
    width: 25.6vw;
    height: 19.2vw;
    border-radius: 1.6vw;
    object-fit: cover;
    margin-right: 3.2vw;
  }
  
  .recommend-content {
    flex: 1;
  }
  
  .recommend-title {
    font-size: 4vw;
    font-weight: 500;
    color: #323233;
    margin-bottom: 1.6vw;
    line-height: 1.4;
  }
  
  .recommend-desc {
    font-size: 3.2vw;
    color: #646566;
    line-height: 1.5;
    margin-bottom: 2.13333vw;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .recommend-meta {
    display: flex;
    align-items: center;
    font-size: 3.2vw;
    color: #969799;
    
    .rating {
      display: flex;
      align-items: center;
      margin-right: 4.26667vw;
      
      .van-icon {
        margin-right: 1.06667vw;
        font-size: 3.2vw;
      }
    }
  }
}

// 活动列表
.activity-list {
  .activity-item {
    background: white;
    border-radius: 2.13333vw;
    padding: 4.26667vw;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    cursor: pointer;
  }
  
  .activity-poster {
    width: 100%;
    height: 34.13333vw;
    border-radius: 1.6vw;
    object-fit: cover;
    margin-bottom: 3.2vw;
  }
  
  .activity-title {
    font-size: 4vw;
    font-weight: 500;
    color: #323233;
    margin-bottom: 2.13333vw;
  }
  
  .activity-desc {
    font-size: 3.2vw;
    color: #646566;
    line-height: 1.5;
    margin-bottom: 3.2vw;
  }
  
  .activity-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 3.2vw;
    
    .deadline {
      color: #969799;
    }
    
    .join-btn {
      color: #1989fa;
      font-weight: 500;
      display: flex;
      align-items: center;
      
      .van-icon {
        margin-left: 1.06667vw;
        font-size: 2.66667vw;
      }
    }
  }
}
</style>
